package a09_贪心算法;

import java.util.Arrays;

/**
 * <p>
 * a09_K次取反后最大化的数组和复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/11
 */
public class a09_K次取反后最大化的数组和复习3 {
    public static void main(String[] args) {
        int[] nums = new int[]{4,2,3};
        System.out.println(largestSumAfterKNegations(nums, 1));
    }
    public static int largestSumAfterKNegations(int[] nums, int k) {
        //负数绝对值从大到小，全部的绝对值最小的
        Integer[] integers = Arrays.stream(nums)
                .boxed()
                .toArray(Integer[]::new);
        Arrays.sort(integers, (item1,item2) -> Math.abs(item2) - Math.abs(item1));

        for (int i = 0; k > 0 && i < integers.length; i++) {
            if(integers[i] < 0){
                integers[i] = integers[i] *  -1;
                k--;
            }
        }

        if (k > 0){
            if(k % 2 == 1){
                integers[integers.length-1] = integers[integers.length-1] * -1;
            }
        }

        return Arrays.stream(integers).mapToInt(i -> i).sum();
    }
}
